import router from './router';
import store from './store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getVerifyToken } from "api/auth";
import {hasPermission} from 'utils/sift';

const whiteList = ['/login', '/403', '/404', '/500'];

router.beforeEach((to, from, next) => {
    NProgress.start();
    
    getVerifyToken({id:store.getters.store_token}).then(response => {
        if(store.getters.store_token && response.data.code == 0) {
            if(to.path === '/login') {
                next({path: '/'});
            } else {
                if(store.getters.store_name === ''){
                    store.dispatch('GetUserInfo').then(res => {
                        const permissions = res.permissions;
                        store.dispatch('FormatRoutes', permissions).then(() => {
                            router.addRoutes(store.getters.store_add_routers);
                            next(to.path);
                        });
                    }).catch(error => {
                        store.dispatch("Logout");
                    });
                } else {
                    if(hasPermission(store.getters.store_permissions, to)) {
                        next();
                    } else {
                        next({
                            path: '/403'
                        });
                    }
                }
            }
        } else {
            if(whiteList.indexOf(to.path) !== -1) {
                next();
            } else {
                next('/login');
                NProgress.done();
            }
        }
    }).catch(error => {
        if(whiteList.indexOf(to.path) !== -1) {
            next();
        } else {
            next('/login');
            NProgress.done();
        }
    });
});

router.afterEach(() => {
    NProgress.done();
});

